package org.styx.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.styx.datasource.DataSourceProperties;
import org.styx.datasource.DynamicDataSource;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class DataSourceConfig {
    private final DataSourceProperties prop;
    private Map<Object, Object> dataSourceMap = new HashMap<>(8);

    @Bean("dynamicDataSource")
    public DynamicDataSource dataSource(){
        DynamicDataSource dds=new DynamicDataSource();
        HikariDataSource hds=new HikariDataSource();
        hds.setUsername(this.prop.getUsername());
        hds.setPassword(this.prop.getPassword());
        hds.setDriverClassName(this.prop.getDriverClassName());
        hds.setJdbcUrl(this.prop.getUrl());
        dds.setDefaultTargetDataSource(hds);
        dataSourceMap.put(0,hds);
        dds.setTargetDataSources(dataSourceMap);
        return dds;
    }

    /**
     * 查询数据库组装数据源
     */
    @PostConstruct
    public void init(){
        DriverManagerDataSource dmds=new DriverManagerDataSource();
        dmds.setUrl(this.prop.getUrl());
        dmds.setDriverClassName(this.prop.getDriverClassName());
        dmds.setUsername(this.prop.getUsername());
        dmds.setPassword(this.prop.getPassword());

        List<Map<String,Object>> dbList=new JdbcTemplate(dmds).queryForList("select * from db_datasource");
        log.info("开始->初始化数据源");
        Optional.of(dbList).ifPresent(list->list.forEach(db->{
            log.info("数据源:{}->驱动:{}", db.get("name"),
                db.get("driver_class_name"));
            HikariDataSource hds=new HikariDataSource();
            hds.setJdbcUrl(String.valueOf(db.get("url")));
            hds.setDriverClassName(String.valueOf(db.get("driver_class_name")));
            hds.setUsername(String.valueOf(db.get("username")));
            hds.setPassword(String.valueOf(db.get("password")));
            dataSourceMap.put(db.get("id"),hds);
        }));
        log.info("完毕 -> 初始化动态数据源,共计 {} 条", this.dataSourceMap.size());
    }
    /**
     * 重新加载数据源配置
     */
    public Boolean reload() {
        this.init();
        DynamicDataSource dataSource = this.dataSource();
        dataSource.setTargetDataSources(this.dataSourceMap);
        dataSource.afterPropertiesSet();
        return Boolean.FALSE;
    }
}
